package cc.mrbird.febs.system.controller;

import cc.mrbird.febs.common.authentication.ShiroHelper;
import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.common.entity.FebsConstant;
import cc.mrbird.febs.common.utils.DateUtil;
import cc.mrbird.febs.common.utils.FebsUtil;
import cc.mrbird.febs.customer.entity.*;
import cc.mrbird.febs.customer.service.*;
import cc.mrbird.febs.system.entity.User;
import cc.mrbird.febs.system.service.IUserDataPermissionService;
import cc.mrbird.febs.system.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.ExpiredSessionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author MrBird
 */
@Controller("systemView")
@RequiredArgsConstructor
public class ViewController extends BaseController {

    private final IUserService userService;
    private final ShiroHelper shiroHelper;
    private final IUserDataPermissionService userDataPermissionService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private ICustomerService customerService;

    @Autowired
    private IShareService shareService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IIncomeService iIncomeService;

    @GetMapping("login")
    @ResponseBody
    public Object login(HttpServletRequest request) {
        if (FebsUtil.isAjaxRequest(request)) {
            throw new ExpiredSessionException();
        } else {
            ModelAndView mav = new ModelAndView();
            mav.setViewName(FebsUtil.view("login"));
            return mav;
        }
    }

    @GetMapping("unauthorized")
    public String unauthorized() {
        return FebsUtil.view("error/403");
    }


    @GetMapping("/")
    public String redirectIndex() {
        return "redirect:/index";
    }

    @GetMapping("index")
    public String index(Model model) {
        AuthorizationInfo authorizationInfo = shiroHelper.getCurrentUserAuthorizationInfo();
        User user = super.getCurrentUser();
        User currentUserDetail = userService.findByName(user.getUsername());
        currentUserDetail.setPassword("It's a secret");
        model.addAttribute("user", currentUserDetail);
        model.addAttribute("permissions", authorizationInfo.getStringPermissions());
        model.addAttribute("roles", authorizationInfo.getRoles());
        return "index";
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "layout")
    public String layout() {
        return FebsUtil.view("layout");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "password/update")
    public String passwordUpdate() {
        return FebsUtil.view("system/user/passwordUpdate");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "user/profile")
    public String userProfile() {
        return FebsUtil.view("system/user/userProfile");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "user/avatar")
    public String userAvatar() {
        return FebsUtil.view("system/user/avatar");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "user/profile/update")
    public String profileUpdate() {
        return FebsUtil.view("system/user/profileUpdate");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/user")
    @RequiresPermissions("user:view")
    public String systemUser() {
        return FebsUtil.view("system/user/user");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/user/add")
    @RequiresPermissions("user:add")
    public String systemUserAdd() {
        return FebsUtil.view("system/user/userAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/user/detail/{username}")
    @RequiresPermissions("user:view")
    public String systemUserDetail(@PathVariable String username, Model model) {
        resolveUserModel(username, model, true);
        return FebsUtil.view("system/user/userDetail");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/user/update/{username}")
    @RequiresPermissions("user:update")
    public String systemUserUpdate(@PathVariable String username, Model model) {
        resolveUserModel(username, model, false);
        return FebsUtil.view("system/user/userUpdate");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/role")
    @RequiresPermissions("role:view")
    public String systemRole() {
        return FebsUtil.view("system/role/role");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/menu")
    @RequiresPermissions("menu:view")
    public String systemMenu() {
        return FebsUtil.view("system/menu/menu");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/dept")
    @RequiresPermissions("dept:view")
    public String systemDept() {
        return FebsUtil.view("system/dept/dept");
    }

    @RequestMapping(FebsConstant.VIEW_PREFIX + "index")
    public String pageIndex() {
        return FebsUtil.view("index");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "404")
    public String error404() {
        return FebsUtil.view("error/404");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "403")
    public String error403() {
        return FebsUtil.view("error/403");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "500")
    public String error500() {
        return FebsUtil.view("error/500");
    }

    private void resolveUserModel(String username, Model model, Boolean transform) {
        User user = userService.findByName(username);
        String deptIds = userDataPermissionService.findByUserId(String.valueOf(user.getUserId()));
        user.setDeptIds(deptIds);
        model.addAttribute("user", user);
        if (transform) {
            String sex = user.getSex();
            if (User.SEX_MALE.equals(sex)) {
                user.setSex("男");
            } else if (User.SEX_FEMALE.equals(sex)) {
                user.setSex("女");
            } else {
                user.setSex("保密");
            }
        }
        if (user.getLastLoginTime() != null) {
            model.addAttribute("lastLoginTime", DateUtil.getDateFormat(user.getLastLoginTime(), DateUtil.FULL_TIME_SPLIT_PATTERN));
        }
    }

    /**
     * @Author wangke
     * @Description 活动管理模块
     * @Date 15:28 2020/11/2
     * @Param
     * @return
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "system/activityList")
    @RequiresPermissions("activity:view")
    public String toActivityList(){
        return FebsUtil.view("system/activity/activityList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/activity/add")
    @RequiresPermissions("activity:view")
    public String toActivityAdd(){
        return FebsUtil.view("system/activity/activityAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/activity/update/{tactivityId}")
    @RequiresPermissions("activity:view")
    public String toActivityUpdate(@PathVariable String tactivityId,Model model){
        Activity byId = activityService.getById(tactivityId);
        model.addAttribute("activity",byId);
        return FebsUtil.view("system/activity/activityUpdate");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/activity/updateContent/{tactivityId}")
    @RequiresPermissions("activity:view")
    public String toUpdateContent(@PathVariable String tactivityId,Model model){
        Activity byId = activityService.getById(tactivityId);
        model.addAttribute("activity",byId);
        return FebsUtil.view("system/activity/activityContent");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/activity/activityView/{tactivityId}")
    @RequiresPermissions("activity:view")
    public String toActivityContent(@PathVariable String tactivityId,Model model){
        Activity byId = activityService.getById(tactivityId);
        model.addAttribute("activity",byId);
        return FebsUtil.view("system/activity/activityView");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/activity/toPosition")
    @RequiresPermissions("activity:view")
    public String toPosition(){
        return FebsUtil.view("system/activity/position");
    }


    @GetMapping(FebsConstant.VIEW_PREFIX + "system/wx")
    public String wx(){
        return FebsUtil.view("system/wx/wxpay");
    }

    /**
     * @Author wangke
     * @Description 客户管理页面跳转
     * @Date 16:17 2020/11/4
     * @Param
     * @return
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "system/customer/customerList")
    @RequiresPermissions("customer:view")
    public String toCustomer(){
        return FebsUtil.view("system/customer/customer");
    }

    /**
     * @Author wangke
     * @Description 去客户详情页面
     * @Date 16:18 2020/11/4
     * @Param
     * @return
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "system/customer/customerView/{nickname}")
    @RequiresPermissions("customer:view")
    public String toCustomerView(@PathVariable String nickname, Model model){
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        wrapper.eq("nickName",nickname);
        Customer one = customerService.getOne(wrapper);
        model.addAttribute("Customer",one);
        return FebsUtil.view("system/customer/customerView");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/customer/withdraw/{customerId}")
    @RequiresPermissions("customer:view")
    public String toWithDrawPrice(@PathVariable String customerId, Model model){
        Customer byId = customerService.getById(customerId);
        model.addAttribute("customer",byId);
        return FebsUtil.view("system/customer/withDrawPrice");
    }

    /**
     * @Author wangke
     * @Description 去订单管理页面
     * @Date 16:18 2020/11/4
     * @Param
     * @return
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "system/order/orderList")
    @RequiresPermissions("order:view")
    public String toOrder(){
        return FebsUtil.view("system/order/orderList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/order/orderView/{orderId}")
    @RequiresPermissions("order:view")
    public String toOrderView(@PathVariable String orderId,Model model){
        Order order = orderService.getById(orderId);
        Customer customer = customerService.getOne(new QueryWrapper<Customer>().lambda().eq(Customer::getOpenid,order.getOpenId()));
        order.setNickName(customer.getNickname());
        order.setTrueName(customer.getTrueName());
        model.addAttribute("order",order);
        return FebsUtil.view("system/order/orderView");
    }

    /**
     * @Author wangke
     * @Description 去收入详情界面
     * @Date 16:39 2020/11/5
     * @Param 
     * @return 
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "system/income/update/{incomeId}")
    @RequiresPermissions("income:view")
    public String toIncome(@PathVariable String incomeId,Model model){
        Income byId = iIncomeService.getById(incomeId);
        model.addAttribute("income",byId);
        return FebsUtil.view("system/income/incomeUpdate");
    }


    @GetMapping(FebsConstant.VIEW_PREFIX + "system/income/incomeList/{customerId}")
    @RequiresPermissions("income:view")
    public String toUpdateIncome(@PathVariable String customerId,Model model){
        model.addAttribute("customerId",customerId);
        return FebsUtil.view("system/income/incomeList");
    }
    
    /**
     * @Author wangke
     * @Description 去分享界面
     * @Date 17:36 2020/11/6
     * @Param 
     * @return 
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "system/share/shareList")
    @RequiresPermissions("share:view")
    public String toShare(){
        return FebsUtil.view("system/share/shareList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/share/shareView/{shareId}")
    @RequiresPermissions("share:view")
    public String toShareView(@PathVariable String shareId,Model model){
        Share share = shareService.getById(shareId);
        model.addAttribute("share",share);
        return FebsUtil.view("system/share/shareView");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/share/updateShare/{shareId}")
    @RequiresPermissions("share:view")
    public String toShareUpdate(@PathVariable String shareId,Model model){
        Share byId = shareService.getById(shareId);
        model.addAttribute("share",byId);
        return FebsUtil.view("system/share/shareUpdate");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/wxShare")
    public String toWxShare(){
        return FebsUtil.view("system/wx/index");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/wxPay")
    public String toWxPay(){
        return FebsUtil.view("system/wx/wxpay");
    }




}
